package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.user.dto.AddressDTO;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderFormDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.entity.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    OrderDetailServiceImpl detailService;

    @Autowired
    OrderLogisticsServiceImpl logisticsService;

    @Autowired
    ItemClient itemClient;

    @Autowired
    UserClient userClient;

    //一共要操作三张表
    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderDTO) {
        //1.order表
        Order order = new Order();
        //1.1从上下文拿出用户id
        order.setUserId(UserContext.getUser().getId());
        //1.2计算总金额
        //获取购物车
        Map<Long, Integer> carts = orderDTO.getCarts();
        //获取所有的sku详情（价格）
        ArrayList<Long> skuIdList = new ArrayList<>(carts.keySet());
        List<SkuDTO> skuDTOList = itemClient.querySkuByIds(skuIdList);
        //开始计算
        //total是按照分计算的这里
        long total = 0L;
        for (SkuDTO skudto : skuDTOList) {
            //获取单个sku数量
            Integer num = carts.get(skudto.getId());
            total += skudto.getPrice() * num;
        }
        //填写总金额
        order.setTotalFee(total);
        order.setPaymentType(orderDTO.getPaymentType());//支付方式
        order.setPostFee(0L);//全场包邮
        //实际付款金额： 总金额加邮费减去优惠
        order.setActualFee(total+order.getPostFee());
        //设置订单状态：刚下单：为初始化
        order.setStatus(OrderStatus.INIT.getValue());
        //填写订单到数据库
        boolean b = save(order);
        if (!b){
            throw new LyException(500,"订单创建失败");
        }

        //2.写orderDetail
        //订单有多个商品
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        //遍历sku集合，转化为detail
        for (SkuDTO skuDTO:skuDTOList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setImage(StringUtils.substringBefore(skuDTO.getImages(),","));
            orderDetail.setNum(carts.get(skuDTO.getId()));
            orderDetail.setSkuId(skuDTO.getId());
            orderDetail.setSpec(skuDTO.getSpecialSpec());
            orderDetail.setPrice(skuDTO.getPrice());
            orderDetail.setTitle(skuDTO.getTitle());
            orderDetails.add(orderDetail);
        }
        //批量新增
        boolean b1 = detailService.saveBatch(orderDetails);
        if (!b1){
            throw new LyException(500,"创建订单详情失败");
        }

        //3.填写orderLogistics
        //查询收货地址
        AddressDTO addressDTO = userClient.queryAddressById(orderDTO.getAddressId());
        OrderLogistics orderLogistics = addressDTO.toEntity(OrderLogistics.class);
        orderLogistics.setOrderId(order.getOrderId());
        //写入数据库
        boolean b2 = logisticsService.save(orderLogistics);
        if (!b2){
            throw new LyException(500,"订单创建失败");
        }

        // 4.减库存
        try {
            itemClient.deductStock(carts);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());
        }

        System.out.println("订单号：");
        //返回订单号
        System.out.println("订单id为orderid = " + order.getOrderId());
        return order.getOrderId();
    }
}